package view;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import model.Author;
import model.Work;
import model.Work.WorkCategory;

@MultipartConfig
@WebServlet("/Submit")
public class SubmitServlet extends Servlet {

	private static final int MAX_KEY_WORDS = 5;
	private static final long serialVersionUID = -6590756934436019534L;

	@Override
	void fillGetContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		if (request.getSession().getAttribute("author") != null) {
			printForm(out, "", "", WorkCategory.Nenhuma, null, "");
		}
	}

	@Override
	void fillPostContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		Author sessionAuthor = (Author) request.getSession().getAttribute("author");
		if (sessionAuthor != null) {

			long idAuthor = sessionAuthor.getId();
			String title = request.getParameter("title");
			String theme = request.getParameter("theme");
			List<String> keyWords = getkeyWords(request);
			String description = request.getParameter("description");

			byte[] workFile = null;
			String fileName = "";
			Part workFilePart;
			WorkCategory category = WorkCategory.Nenhuma;
			try {
				category = parseWorkCategory(request);
				workFilePart = request.getPart("workFile");
				fileName = getFileName(workFilePart);
				workFile = getBytesFromPart(workFilePart);
				Work work = new Work(idAuthor, title, theme, category, keyWords, description, workFile, fileName);
				work.save();
				out.println(HtmlFactory.createSuccessMessage("Trabalho \"" + title + "\" salvo com sucesso!!!"));
			} catch (Exception e) {
				out.println(HtmlFactory.createErrorMessage(e.getMessage()));
				printForm(out, title, theme, category, keyWords, description);
			}

		}
	}

	private WorkCategory parseWorkCategory(HttpServletRequest request) throws Exception {
		try {
			return WorkCategory.values()[Integer.valueOf(request.getParameter("workCategory"))];
		} catch (IndexOutOfBoundsException ex) {
			throw new Exception("Esta categoria não existe!");
		}
	}

	private String getFileName(Part part) throws Exception {
		for (String content : part.getHeader("content-disposition").split(";")) {
			if (content.trim().startsWith("filename")) {
				return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
			}
		}

		throw new Exception("Não foi possível encontrar o nome do arquivo!");
	}

	private byte[] getBytesFromPart(Part part) throws Exception {
		long fileSize = part.getSize();
		if (fileSize <= Integer.MAX_VALUE) {
			byte[] bytes = new byte[(int) fileSize];
			part.getInputStream().read(bytes, 0, (int) fileSize);
			return bytes;
		} else {
			throw new Exception("Arquivo grande demais!");
		}
	}

	private List<String> getkeyWords(HttpServletRequest request) {
		List<String> keyWords = new ArrayList<>();

		for (int i = 1; i <= MAX_KEY_WORDS; i++) {
			String keyWord = request.getParameter("pc" + i);
			if (keyWord != null && !keyWord.equals("")) {
				keyWords.add(keyWord);
			}
		}

		return keyWords;
	}

	private void printForm(PrintWriter out, String title, String theme, WorkCategory category, List<String> keyWords,
			String description) {
		/* @formatter:off */
		out.println("<form action='Controller' method='POST' enctype='multipart/form-data'>");
		out.println("	<label for='title'>Título:</label>");
		out.println("	<input id='title' type='text' name='title' value='"+title+"'></br>");
		out.println("	<label for='theme'>Tema:</label>");
		out.println("	<input id='theme' type='text' name='theme' value='"+theme+"'></br>");
		out.println("	<label for='workCategory'>Categoria:</label>");
		out.println(	HtmlFactory.createCategoryCombo(category)+"</br>");
		
		out.println("	<label>Palavras-Chave:</label>");
		int i = 1;
		if(keyWords != null){
			for(String keyWord : keyWords){
				out.println("	<input type='text' name='pc"+ i++ +"' value='"+keyWord+"' size='14'>");
			}
		}
		while(i <= MAX_KEY_WORDS){
			out.println("	<input type='text' name='pc"+ i++ +"'>");
		}
		out.println("	</br>");
		
		out.println("	<label for='description' style='vertical-align: top;'>Descrição:</label>");
		out.println("	<textarea id='description' name='description' rows='5' cols='60'>"+description+"</textarea></br>");
		out.println("	<label for='file'>Arquivo:</label>");
		out.println("	<input id='file' type='file' name='workFile'></br>");
		out.println("	<input type='submit' name='button' value='Submeter' style='margin-left: 145px;'>");
		out.println("</form>");
		/* @formatter:on */
	}
}
